package com.eastidea.live.controller.rest;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.bson.types.ObjectId;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.eastidea.live.dao.AppDao;
import com.eastidea.live.entity.AppApplication;
import com.eastidea.live.entity.AppUser;
import com.eastidea.live.ot.AppOt;
import com.eastidea.live.service.AppService;
import com.eastidea.live.to.AppTo;
import com.eastidea.live.util.Constant;
import com.eastidea.live.util.QrUtil;
import com.eastidea.live.util.RequestUtil;
import com.eastidea.live.util.StringUtil;

@Controller
@SessionAttributes("user")
@RequestMapping(value = Constant.API_REST_V1 + "/apps")
public class AppRestController {

    Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private AppService appService;
    @Resource
    private AppDao appDao;
    
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> list(@ModelAttribute("user") AppUser user, ModelMap modelMap, HttpServletRequest request) {    	
        Map<String, Object> res = new HashMap<String, Object>();

		Long userId = user.getId();

        DetachedCriteria dc = DetachedCriteria.forClass(AppApplication.class);
        //dc.setFetchMode("strCompany", FetchMode.JOIN);
        //dc.setFetchMode("appSubscriptions", FetchMode.JOIN);
		dc.add(Restrictions.eq("appCompany", user.getAppCompany()));
        dc.add(Restrictions.eq("status", 1));
        dc.addOrder(Order.desc("id"));
        dc.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

        List<AppApplication> poList = appDao.findByCriteria(dc);
        List<AppTo> ls = new ArrayList<AppTo>();
        for (AppApplication po : poList) {
        	ls.add(AppOt.GenerateAppTo(po));
        }

        res.put("success", true);
        res.put("apps", ls);
        res.put("email", user.getEmail());
		return res;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> detail(@ModelAttribute("user") AppUser user, @PathVariable("id") Long id, ModelMap modelMap, HttpServletRequest request) {
    	Map<String, Object> res = new HashMap<String, Object>();
    	
    	AppTo to = null;

        if (id != null) {
			DetachedCriteria dc = DetachedCriteria.forClass(AppApplication.class);
			dc.add(Restrictions.eq("id", Long.valueOf(id)));
			dc.add(Restrictions.eq("status", 1));
			dc.setFetchMode("appSubscriptions", FetchMode.JOIN);
			dc.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );
			List<AppApplication> poList = appDao.findByCriteria(dc);
			
			to  = AppOt.GenerateAppTo(poList.get(0));
        }
        res.put("success", true);
        res.put("app", to);
        res.put("email", user.getEmail());
        return res;
    }

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> save(@ModelAttribute("user") AppUser user, @RequestBody JSONObject jsonObj,
			HttpServletRequest request, ModelMap modelMap) throws UnknownHostException {
		Map<String, Object> res = new HashMap<String, Object>();

		Long userId = user.getId();
		
    	AppApplication app = new AppApplication();
    	
		app.setName(jsonObj.getString("name"));
		app.setDescr((jsonObj.containsKey("descr"))?jsonObj.getString("descr"):"");
		app.setStatus(1);
		app.setAppCompany(user.getAppCompany());
    	appDao.save(app);
    	
		String path = "upload/qr/" + app.getId() + "-run.jpg";
		QrUtil.genQr(
				Constant.DISPLAY_ROOT + "index.html#app/" + app.getId() + "/session",
				RequestUtil.getAbsolutePath(request) + path);
		app.setRunQrCode(path);
		appDao.update(app);

		res.put("success", true);
		return res;
    }

	@RequestMapping(method = RequestMethod.PUT)
	@ResponseBody
	public Map<String, Object> update(@ModelAttribute("user") AppUser user, @RequestBody JSONObject jsonObj,
			HttpServletRequest request, ModelMap modelMap) throws IOException {
		Map<String, Object> res = new HashMap<String, Object>();
		
		Long userId = user.getId();
		
		Long id = Long.valueOf(jsonObj.getString("id"));
    	AppApplication app = appDao.get(id);
    	if (app.getAppCompany().getId().longValue() == user.getAppCompany().getId().longValue()) {
    		app.setName(jsonObj.getString("name"));
    		app.setDescr(jsonObj.getString("descr"));
        	appDao.update(app);
    	} else {
			res.put("success", false);
    	}
		res.put("success", true);
		return res;
    }

	@RequestMapping(method = RequestMethod.DELETE)
	@ResponseBody
	public Map<String, Object> delete(@ModelAttribute("user") AppUser user, @RequestBody JSONObject jsonObj,
			ModelMap modelMap, HttpServletRequest request) throws IOException {
		Map<String, Object> res = new HashMap<String, Object>();
		
		Long userId = user.getId();
		
		Long id = Long.valueOf(jsonObj.getString("id"));
    	AppApplication app = appDao.get(id);
    	
    	if (app.getAppCompany().getId().longValue() == user.getAppCompany().getId().longValue()) {
    		app.setStatus(0);
        	appDao.update(app);
    	} else {
			res.put("success", false);
    	}

        res.put("success", true);
        return res;
    }

}
